package com.leyou.auth.task;

import com.leyou.auth.config.JwtProperties;
import com.leyou.auth.mapper.ApplicationInfoMapper;
import com.leyou.common.auth.entity.AppInfo;
import com.leyou.common.auth.utils.JwtUtils;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author Eric
 * @version v1.0
 * @package com.leyou.gateway.task
 * @date 2019/7/9 18:51
 * @description:
 **/
@Component
@Slf4j
@Getter
public class PrivilegeTokenHolder {


    private String token;

    /**
     * token刷新间隔
     */
    private static final long TOKEN_REFRESH_INTERVAL = 86400000L;

    /**
     * token获取失败后重试的间隔
     */
    private static final long TOKEN_RETRY_INTERVAL = 10000L;


    @Autowired
    private JwtProperties prop;
    @Autowired
    private ApplicationInfoMapper applicationInfoMapper;

    @Scheduled(fixedDelay =TOKEN_REFRESH_INTERVAL)
    public void loadToken() throws InterruptedException {
        while (true) {
            try {
                List<Long> targetIdList = applicationInfoMapper.selectTargetIdList(prop.getApp().getId());
                AppInfo appInfo = new AppInfo();
                appInfo.setId(prop.getApp().getId());
                appInfo.setServiceName(prop.getApp().getSecret());
                appInfo.setTargetList(targetIdList);

                this.token = JwtUtils.generateTokenExpireInMinutes(appInfo, prop.getPrivateKey(), prop.getApp().getExpire());
                log.info("授权中心生成token成功！");
                break;
            } catch (Exception e) {
                log.info("授权中心生成token失败！",e.getMessage(),e);
                Thread.sleep(TOKEN_RETRY_INTERVAL);
            }
        }
    }
}
